<?php

class QrcodeImg {
    private $font_path;

    public function __construct() {
        $this->font_path = dirname(__FILE__) . '/skin/PingFang-W4.ttc';
    }

    function chararray($str, $charset = "utf-8") {
        $re['utf-8'] = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
        $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
        $re['gbk'] = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
        $re['big5'] = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
        preg_match_all($re[$charset], $str, $match);
        return $match;
    }

    /* 返回一个字符串在图片中所占的宽度 */
    function charwidth($fontsize, $fontangle, $ttfpath, $char) {
        $box = @imagettfbbox($fontsize, $fontangle, $ttfpath, $char);
        $width = abs(max($box[2], $box[4]) - min($box[0], $box[6]));
        return $width;
    }

    function text_width($fontsize, $fontangle, $ttfpath, $str) {
        $_width = 0;
        $temp = $this->chararray($str);
        foreach ($temp[0] as $k => $v) {
            $w = $this->charwidth($fontsize, $fontangle, $ttfpath, $v);
            $_width += intval($w);
        }

        return $_width;
    }

    /* 这几个变量分别是 字体大小, 角度, 字体名称, 字符串, 预设宽度, 编码 */
    function autowrap($fontsize, $fontangle, $ttfpath, $str, $width, $charset = 'utf-8') {
        $_string = "";
        $_width = 0;
        $temp = $this->chararray($str);
        foreach ($temp[0] as $k => $v) {
            $w = $this->charwidth($fontsize, $fontangle, $ttfpath, $v);
            $_width += intval($w);

            if (($_width >= $width)) {
                $_string .= "\n";
                $_width = 0;
            }
            $_string .= $v;
        }
        $_string = mb_convert_encoding($_string, "html-entities", $charset);

        return $_string;
    }

    function getgoodsma($weid, $uid, $itemid) { // 获取单个商品的小程序码
        $cachename = 'x_goods_' . $weid . '_' . $uid . '_' . $itemid;
        $result = memory('get', $cachename);

        if ($result) {
            return base64_decode($result);
        }

        $xres = DB::fetch_first("SELECT `appid`, `appsecret` FROM " . DB::table('x_list') . " WHERE `login_name` = 'xiaochengxu' AND `weid` = " . $weid);
        if (!empty($xres)) {
            include_once ROOT_PATH . 'web/lib/weixin/wechat.class.php';
            $wechat = new Wechat(array('appid' => $xres['appid'], 'appsecret' => $xres['appsecret']));
            /*$result = $wechat->getWxaCode(
                array(
                    'path' => 'pages/details/details?itemid=1334539365&t=1182',
                    'width' => 430,
                    'auto_color' => false
                )
            );*/
            $result = $wechat->getWxaCodeUnlimit(
                array(
                    'scene' => $uid . ':' . $itemid, // 最大32个可见字符
                    'page' => 'pages/details/details',
                    'width' => 430,
                    'auto_color' => false
                )
            );

            if ($result) {
                memory('set', $cachename, base64_encode($result), -1);
            }

            return $result;
        }

        return false;
    }

    function gethaibao($weid, $uid) { // 获取整个商城的小程序码
        $cachename = 'x_haibao_'.$weid.'_'.$uid ;
        $result = memory('get', $cachename);

        if ($result) {
            return base64_decode($result);
        }

        $xres = DB::fetch_first("SELECT `appid`, `appsecret` FROM " . DB::table('x_list') . " WHERE `login_name` = 'xiaochengxu' AND `weid` = " . $weid);
        if (!empty($xres)) {
            include_once ROOT_PATH . 'web/lib/weixin/wechat.class.php';
            $wechat = new Wechat(array('appid' => $xres['appid'], 'appsecret' => $xres['appsecret']));
            /*$result = $wechat->getWxaCode(
                array(
                    'path' => 'pages/index/index?t=' . $uid,
                    'width' => 430,
                    'auto_color' => false
                )
            );*/
            $result = $wechat->getWxaCodeUnlimit(
                array(
                    'scene' => $uid, // 最大32个可见字符
                    'page' => 'pages/index/index',
                    'width' => 430,
                    'auto_color' => false
                )
            );

            if ($result) {
                memory('set', $cachename, base64_encode($result), -1);
            }

            return $result;
        }

        return false;
    }

    // 生成用户的小程序商城海报(包含用户的小程序二维码)
    function hb($weid, $uid) {
        if (empty($weid) || empty($uid)) return false;

        $x_ma = $this->gethaibao($weid, $uid); // 获取用户的小程序首页二维码
        if ($x_ma) {
            $dst = imagecreatefromstring($x_ma);

            $path = dirname(__FILE__) . '/';
            $name = 'x_' . $uid . '.png';
            $src = $path . $name;
            imagejpeg($dst, $src);

            $x_ma_width = 210;
            $x_ma_height = $x_ma_width;
            $s_src = $this->scalePicture($x_ma_width, $x_ma_height, $path, $name, 1);

            $haibao = $path . 'haibao.png'; // 这个文件不能删除
            $haibao_width = 750;
            $schb = $path . 'schb_' . $uid . '.png';
            $x_ma_left = $haibao_width / 2 - $x_ma_width / 2;
            $x_ma_top = 950;
            $this->ps($haibao, $s_src, 0, $x_ma_left, $x_ma_top, $schb, '', 1);

            $shi = "长按扫码加入";
            $wename = DB::result_first("SELECT `wename` FROM " . DB::table('x_list') . " WHERE `login_name` = 'xiaochengxu' AND `weid` = " . $weid);
            $shi .= $wename;
            $shi_width = $this->text_width(21, 0, $this->font_path, $shi);

            $shi_left = $haibao_width / 2 - $shi_width / 2;
            $shi_top = $x_ma_top + $x_ma_height + 32;
            //$hb = $path . 'hb_' . $uid . '.png';
            $hb_name = '/assets/uploads/hb/' . 'hb_' . $weid . '_' . $uid . '.png';
            $hb = ROOT_PATH . $hb_name;
            $this->font($schb, $shi, 1, $shi_left, $shi_top, $hb, 255, 255, 255, 20, 0);

            return self_host() . $hb_name;
        }

        return false;
    }

    function hb_del($weid, $uid) {
        $hb_name = '/assets/uploads/hb/' . 'hb_' . $weid . '_' . $uid . '.png';
        $hb = ROOT_PATH . $hb_name;
        if (file_exists($hb)) {
            unlink($hb);
        }
    }

    function st($weid, $uid, $param) {
        $itemid = $param['itemid'];
        if (empty($weid) || empty($uid) || empty($itemid)) return false;

        $title_org = "             " . $param['title'];
        $title = $this->autowrap(16, 0, $this->font_path, $title_org, 250, $charset = 'utf-8');

        $picurl = $param['picurl'];
        $original_price = $param['original_price'];
        $coupon_price = $param['coupon_price'];
        $price = $param['price'];

        $path = dirname(__FILE__) . '/';
        $baiban_name = 'baiban_'. $uid . '.png';
        $baiban = $path . $baiban_name;
        $width = 400;
        $height = 580;
        $this->baiban($width, $height, $baiban, 255, 255, 255);

        $goods_picurl_name = 'picurl_' . $uid . '.jpeg';
        $goods_picurl = $path . $goods_picurl_name;
        $dst = imagecreatefromstring(file_get_contents($picurl));
        imagejpeg($dst, $goods_picurl);

        $goods_picurl_width = 400;
        $goods_picurl_height = $goods_picurl_width;
        $s_goods_picurl = $this->scalePicture($goods_picurl_width, $goods_picurl_height, $path, $goods_picurl_name, 1);

        // 画商品图片
        $sc1 = $path . 'sc1_' . $uid . '.png';
        $this->ps($baiban, $s_goods_picurl, 1, 0, 0, $sc1, '', 1);

        // 画圆角的“拼多多”
        $pdd_corner_name = "pdd_corner.png";
        $pdd_corner_width = 55;
        //指定要缩放到的宽度
        $pdd_corner_height = 20;
        //指定要缩放到的高度
        $s_pdd_corner_pic = $this->scalePicture($pdd_corner_width, $pdd_corner_height, $path, $pdd_corner_name, 0, 1);
        $sc2 = $path . 'sc2_' . $uid . '.png';
        $this->ps($sc1, $s_pdd_corner_pic, 1, 10, 415, $sc2, '', 1);

        // 画商品标题
        $sc3 = $path . 'sc3_' . $uid . '.png';
        $this->font($sc2, $title, 1, 10, 435, $sc3, 0, 0, 0, 12, 0);

        // 画商品原价
        $sc4 = $path . 'sc4_' . $uid . '.png';
        $original_price = '原价 ￥' . $original_price;
        $original_price_width = $this->text_width(15, 0, $this->font_path, $original_price);
        $this->font($sc3, $original_price, 1, 10, 520, $sc4, 157, 157, 157, 12, 0);

        // 画中划线
        $sc5 = $path . 'sc5_' . $uid . '.png';
        $this->line($sc4, 1, 8, 514, 10 + $original_price_width, 514, 157, 157, 157, $sc5);

        // 画红色的正方形
        $sc6 = $path . 'sc6_' . $uid . '.png';
        $this->baiban(25, 25, $sc6, 212, 54, 29);
        $sc7 = $path . 'sc7_' . $uid . '.png';
        $this->ps($sc5, $sc6, 1, 10, 535, $sc7, '', 1);

        // 在红色正方形内部画“券”字
        $sc8 = $path . 'sc8_' . $uid . '.png';
        $this->font($sc7, '券', 1, 14, 553, $sc8, 255, 255, 255, 12, 0);

        $coupon_price = explode('.', $coupon_price);
        $coupon_price = '￥' . $coupon_price[0];
        $quan_width = $this->text_width(17, 0, $this->font_path, $coupon_price);
        $quan_width += 8;

        // 画3条红色的线
        $sc9 = $path . 'sc9_' . $uid . '.png';
        $this->line($sc8, 1, 35, 535, 35 + $quan_width, 535, 212, 54, 29, $sc9);
        $sc10 = $path . 'sc10_' . $uid . '.png';
        $this->line($sc9, 1, 35 + $quan_width, 535, 35 + $quan_width, 559, 212, 54, 29, $sc10);
        $sc11 = $path . 'sc11_' . $uid . '.png';
        $this->line($sc10, 1, 35 + $quan_width, 559, 35, 559, 212, 54, 29, $sc11);

        // 画优惠券
        $sc12 = $path . 'sc12_' . $uid . '.png';
        $this->font($sc11, $coupon_price, 1, 35, 553, $sc12, 212, 54, 29, 12, 0);

        // 画券后价
        $sc13 = $path . 'sc13_' . $uid . '.png';
        $this->font($sc12, '券后价', 1, 35 + $quan_width + 10, 555, $sc13, 157, 157, 157, 12, 0);
        $sc14 = $path . 'sc14_' . $uid . '.png';
        $this->font($sc13, '￥', 1, 35 + $quan_width + 65, 555, $sc14, 212, 54, 29, 10, 0);
        $sc15 = $path . 'sc15_' . $uid . '.png';
        $this->font($sc14, $price, 1, 35 + $quan_width + 80, 555, $sc15, 212, 54, 29, 18, 0);


        // 画二维码的边框
        $sc16 = $path . 'sc16_' . $uid . '.png';
        $this->line($sc15, 1, 250, 425, 265, 425, 163, 82, 89, $sc16);
        $sc17 = $path . 'sc17_' . $uid . '.png';
        $this->line($sc16, 1, 250, 425, 250, 440, 163, 82, 89, $sc17);
        $sc18 = $path . 'sc18_' . $uid . '.png';
        $this->line($sc17, 1, 380, 425, 365, 425, 163, 82, 89, $sc18);
        $sc19 = $path . 'sc19_' . $uid . '.png';
        $this->line($sc18, 1, 380, 425, 380, 440, 163, 82, 89, $sc19);
        $sc20 = $path . 'sc20_' . $uid . '.png';
        $this->line($sc19, 1, 380, 555, 365, 555, 163, 82, 89, $sc20);
        $sc21 = $path . 'sc21_' . $uid . '.png';
        $this->line($sc20, 1, 380, 555, 380, 540, 163, 82, 89, $sc21);
        $sc22 = $path . 'sc22_' . $uid . '.png';
        $this->line($sc21, 1, 250, 555, 265, 555, 163, 82, 89, $sc22);
        $sc23 = $path . 'sc23_' . $uid . '.png';
        $this->line($sc22, 1, 250, 555, 250, 540, 163, 82, 89, $sc23);
        $sc24 = $path . 'sc24_' . $uid . '.png';
        $this->font($sc23, '长按识别二维码', 1, 270, 560, $sc24, 163, 82, 89, 10, 0);

        // 画二维码
        $x_goodsma = $this->getgoodsma($weid, $uid, $itemid);
        if ($x_goodsma) {
            $dst_goods_ma = imagecreatefromstring($x_goodsma);

            $goodsma_name = 'x_goodsma_' . $uid . '.png';
            $src_goodsma = $path . $goodsma_name;
            imagejpeg($dst_goods_ma, $src_goodsma);

            $goodsma_width = 100;
            $goodsma_height = $goodsma_width;

            $s_src_goodsma = $this->scalePicture($goodsma_width, $goodsma_height, $path, $goodsma_name, 1);

            //$st = $path . 'st_' . $uid . '.png';
            $st_name = '/assets/uploads/st/' . 'st_' . $weid . '_' . $uid . '_' . $itemid . '.png';
            $st = ROOT_PATH . $st_name;
            $this->ps($sc24, $s_src_goodsma, 1, 265, 440, $st, '', 1);

            return self_host() . $st_name;
        }

        return false;
    }

    function st_del($weid, $uid, $itemid) {
        $st_name = '/assets/uploads/st/' . 'st_' . $weid . '_' . $uid . '_' . $itemid . '.png';
        $st = ROOT_PATH . $st_name;
        if (file_exists($st)) {
            unlink($st);
        }
    }

    function scalePicture($maxW, $maxH, $path, $name, $state, $white_bg = 0) {
        $pre = 's_';
        $s_src = $path . $pre . $name;
        //缩小之后的图像的前缀

        // 准备画布、画笔、颜料

        //获取图像的详细信息
        $src = $path . $name;
        $info = getimagesize($src);
        //根据用户上传的图像，生成相对应类型的画布

        switch ($info[2]) {
            case 1:
                //生成gif格式画布
                $oldImg = imagecreatefromgif($src);
                break;
            case 2:
                //生成jpg格式画布
                $oldImg = imagecreatefromjpeg($src);
                break;
            case 3:
                //生成png格式画布
                $oldImg = imagecreatefrompng($src);
                break;
        }
        //获取原图的宽高
        $oldW = imagesx($oldImg);
        $oldH = imagesy($oldImg);
        //判断那个边比较长，利用较长的边求得比例

        if ($oldW > $oldH) {
            //求得比例
            $b = $oldW / $maxW;
        } else {
            //求得比例
            $b = $oldH / $maxH;
        }
        //获取缩放之后的宽高
        $newW = $oldW / $b;
        $newH = $oldH / $b;

        //根据缩放之后的宽高，生成指定大小的画布
        $newImg = imagecreatetruecolor($newW, $newH);

        // 是否添加白色的背景
        if (1 == $white_bg) {
            $bg = imagecolorallocate($newImg, 255, 255, 255);
            imagefilledrectangle($newImg, 0, 0, $newW, $newH, $bg);
        }

        // 开始绘画
        //将原图缩放到新图当中
        imagecopyresampled($newImg, $oldImg, 0, 0, 0, 0, $newW, $newH, $oldW, $oldH);
        // 输出图像

        switch ($info[2]) {
            case 1:
                imagegif($newImg, $s_src);
                break;

            case 2:
                imagejpeg($newImg, $s_src);
                break;

            case 3:
                imagepng($newImg, $s_src);
                break;
        }

        // 释放资源
        imagedestroy($oldImg);
        imagedestroy($newImg);
        if (!empty($state)) {
            unlink($src);
        }

        return $s_src; // 缩放以后的路径
    }

    function ps($dst_path, $src_path, $state, $left, $top, $ps, $two, $state2){
        $dst = imagecreatefromstring(file_get_contents($dst_path));

        if (isset($two) && !empty($two)) {
            $src = imagecreatefromstring($two);
        } else {
            $src = imagecreatefromstring(file_get_contents($src_path));
        }

        //获取水印图片的宽高
        list($src_w, $src_h) = getimagesize($src_path);
        //将水印图片复制到目标图片上，最后个参数50是设置透明度，这里实现半透明效果
        imagecopymerge($dst, $src, $left, $top, 0, 0, $src_w, $src_h, 100);
        //如果水印图片本身带透明色，则使用imagecopy方法
        //imagecopy($dst, $src, 10, 10, 0, 0, $src_w, $src_h);
        //输出图片
        if (substr_count(strtolower($ps), 'gif') == 1) {
            imagegif($dst, $ps);
        } else if (substr_count(strtolower($ps), 'png') == 1) {
            imagepng($dst, $ps);
        } else if (substr_count(strtolower($ps), 'jpg') == 1) {
            imagejpeg($dst, $ps);
        } else if (substr_count(strtolower($ps), 'jpeg') == 1) {
            imagejpeg($dst, $ps);
        }

        if ($state == 1) {
            unlink($dst_path);
        }

        if (isset($state2) && !empty($state2)) {
            unlink($src_path);
        }

        imagedestroy($dst);
        imagedestroy($src);
    }

    function font($src_path, $text, $state, $left, $top, $ps, $red, $green, $blue, $size, $rote) {
        //创建图片的实例
        $dst3 = imagecreatefromstring(file_get_contents($src_path));
        //打上文字
        $font = $this->font_path;//字体
        $black = imagecolorallocate($dst3, $red, $green, $blue);//字体颜色
        imagefttext($dst3, $size, $rote, $left, $top, $black, $font, $text);
        //输出图片
        if (substr_count($ps, 'gif') == 1) {
            imagegif($dst3, $ps);
        } else if (substr_count($ps, 'png') == 1) {
            imagepng($dst3, $ps);
        } else if (substr_count($ps, 'jpg') == 1) {
            imagejpeg($dst3, $ps);
        } else if (substr_count($ps, 'jpeg') == 1) {
            imagejpeg($dst3, $ps);
        }

        if ($state == 1) {
            unlink($src_path);
        }

        imagedestroy($dst3);
    }

    function baiban($width, $height, $baiban, $red, $green, $blue) {
        $im = imagecreatetruecolor($width, $height);

        $black = imagecolorallocate($im, $red, $green, $blue);
        imagefilledrectangle($im, 0, 0, $width, $height, $black);

        if (substr_count(strtolower($baiban), 'gif') == 1) {
            imagegif($im, $baiban);
        } else if (substr_count(strtolower($baiban), 'png') == 1) {
            imagepng($im, $baiban);
        } else if (substr_count(strtolower($baiban), 'jpg') == 1) {
            imagejpeg($im, $baiban);
        } else if (substr_count(strtolower($baiban), 'jpeg') == 1) {
            imagejpeg($im, $baiban);
        }

        imagedestroy($im);
    }

    function line($src, $state, $x1, $y1, $x2, $y2, $red, $green, $blue, $mubiao) {
        $im = imagecreatefromstring(file_get_contents($src));

        $color = imagecolorallocate($im, $red, $green, $blue);
        imageline($im, $x1, $y1, $x2, $y2, $color);

        if (substr_count(strtolower($mubiao), 'gif') == 1) {
            imagegif($im, $mubiao);
        } else if (substr_count(strtolower($mubiao), 'png') == 1) {
            imagepng($im, $mubiao);
        } else if (substr_count(strtolower($mubiao), 'jpg') == 1) {
            imagejpeg($im, $mubiao);
        } else if (substr_count(strtolower($mubiao), 'jpeg') == 1) {
            imagejpeg($im, $mubiao);
        }

        if ($state == 1) {
            unlink($src);
        }

        imagedestroy($im);
    }

    function base64EncodeImage($image_file) {
        $image_info = getimagesize($image_file);
        $image_data = fread(fopen($image_file, 'r'), filesize($image_file));

        if ($image_data) {
            $base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
            return $base64_image;
        }

        return false;
    }
}
?>